package com.wanxi.generictype.treeset2;

import com.wanxi.generictype.treeset2.Student;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetSort {
    public static void main(String[] args) {
        Student student1 = new Student("陈明", 28);
        Student student2 = new Student("王海云", 25);
        Student student3 = new Student("江明", 28);
        Student student4 = new Student("刘大姐", 29);
        Student student5 = new Student("后悔", 30);
        Student student6 = new Student("钟鸣一", 32);
        Student student7 = new Student("AB", 28);
        Student student8 = new Student("AA", 28);
        Student student9 = new Student("BB", 28);

//测试定制排序
        /**
         * 一个年龄、名字按照从小到大排序，先比较年龄，再比较名字。如果需要从大到小排序，则负-相应的属性的（返回值）；
         */
        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 == o2) {
                    return 0;
                }
                if (o1 instanceof Student && o2 instanceof Student) {

                    Student s1 = (Student) o1;
                    Student s2 = (Student) o2;

                    int value = s1.getAge() - s2.getAge();

                    if (value != 0) {
                        return value;
                    }
                    return s1.getName().compareTo(s2.getName());
                }
                else {
                    throw new RuntimeException("类型不一样");
                }
            }
        };

//测试自然排序法。
        Set set = new TreeSet(comparator);

        set.add(student1);
        set.add(student2);
        set.add(student3);
        set.add(student4);
        set.add(student5);
        set.add(student6);
        set.add(student7);
        set.add(student8);
        set.add(student9);


//        System.out.println(set);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }


    }
}
